package com.ky.study.controller;


import cn.hutool.core.convert.NumberWithFormat;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ky.common.config.SystemConfig;
import com.ky.common.param.ArticleAdd;
import com.ky.common.util.JwtUtil;
import com.ky.common.vo.R;
import com.ky.study.entity.Article;
import com.ky.study.entity.Static;
import com.ky.study.mapper.ArticleMapper;
import com.ky.study.mapper.StaticMapper;
import com.ky.study.service.impl.StaticServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 文章表 前端控制器
 * </p>
 *
 * @author wgz
 * @since 2024-06-15
 */
@RestController
@RequestMapping("/study/article")
public class ArticleController {
    @Autowired
    ArticleMapper articleMapper;
    @Autowired
    StaticMapper staticMapper;
    @Autowired
    StaticServiceImpl staticService;

    @RequestMapping("/all")
    public R all() {
        // List<Article> articles1 = articleMapper.selectList(null);
        // List<ArticleVO> articleVOS = new ArrayList<>();
        //
        // //遍历集合articles1
        // for (Article article : articles1) {
        //     ArticleVO articleVO = new ArticleVO();
        //     QueryWrapper<Static> staticQueryWrapper = new QueryWrapper<>();
        //     staticQueryWrapper.eq("article_id",article.getArticleId());
        //     List<Static> statics = staticMapper.selectList(staticQueryWrapper);
        //     articleVO.setArticleId(article.getArticleId());
        //     articleVO.setTitle(article.getTitle());
        //     articleVO.setContent(article.getContent());
        //     articleVO.setCategory(article.getCategory());
        //     articleVO.setCreatedAt(article.getCreatedAt());
        //     articleVO.setStatus(article.getStatus());
        //     articleVO.setViews(article.getViews());
        //     articleVO.setCommentsCount(statics.size());
        //     articleVO.setStaticList(statics);
        //     articleVOS.add(articleVO);
        // }
        // // List<ArticleVO> articles = articleMapper.selectArticleWithStatics();
        List<Article> articles = articleMapper.selectList(null);
        return R.ok(articles);
    }

    @RequestMapping("/search")
    public R search(String keyword) {
        QueryWrapper<Article> articleQueryWrapper = new QueryWrapper<>();
        articleQueryWrapper.like("title", keyword).or().like("content", keyword);
        articleQueryWrapper.in("category", "备考经验", "案例分析", "快题", "建筑史", "技术");
        List<Article> articles = articleMapper.selectList(articleQueryWrapper);
        return R.ok(articles);
    }

    @RequestMapping("/bkjy")
    public R bkjy() {
        QueryWrapper<Article> articleQueryWrapper = new QueryWrapper<>();
        articleQueryWrapper.eq("category", "备考经验");
        List<Article> articles = articleMapper.selectList(articleQueryWrapper);
        return R.ok(articles);
    }

    @RequestMapping("/alfx")
    public R alfx() {
        QueryWrapper<Article> articleQueryWrapper = new QueryWrapper<>();
        articleQueryWrapper.eq("category", "案例分析");
        List<Article> articles = articleMapper.selectList(articleQueryWrapper);
        return R.ok(articles);
    }

    @RequestMapping("/kt")
    public R kt() {
        QueryWrapper<Article> articleQueryWrapper = new QueryWrapper<>();
        articleQueryWrapper.eq("category", "快题");
        List<Article> articles = articleMapper.selectList(articleQueryWrapper);
        return R.ok(articles);
    }

    @RequestMapping("/jzs")
    public R jzs() {
        QueryWrapper<Article> articleQueryWrapper = new QueryWrapper<>();
        articleQueryWrapper.eq("category", "建筑史");
        List<Article> articles = articleMapper.selectList(articleQueryWrapper);
        return R.ok(articles);
    }

    @RequestMapping("/js")
    public R js() {
        QueryWrapper<Article> articleQueryWrapper = new QueryWrapper<>();
        articleQueryWrapper.eq("category", "技术");
        List<Article> articles = articleMapper.selectList(articleQueryWrapper);
        return R.ok(articles);
    }

    @RequestMapping("/selectByArticleId/{articleId}")
    public R selectByArticleId(@PathVariable int articleId) {
        QueryWrapper<Article> articleQueryWrapper = new QueryWrapper<>();
        articleQueryWrapper.eq("article_id", articleId);
        return R.ok(articleMapper.selectOne(articleQueryWrapper));
    }

    @RequestMapping("/addViews/{articleId}")
    public R addViews(@PathVariable int articleId) {
        QueryWrapper<Article> articleQueryWrapper = new QueryWrapper<>();
        articleQueryWrapper.eq("article_id", articleId);
        Article article = articleMapper.selectOne(articleQueryWrapper);
        article.setViews(article.getViews() + 1);
        articleMapper.update(article, articleQueryWrapper);
        return R.ok(article);
    }

    // 点赞
    @RequestMapping("/goods/{articleId}")
    public R addGoods(@PathVariable int articleId) {
        QueryWrapper<Article> articleQueryWrapper = new QueryWrapper<>();
        articleQueryWrapper.eq("article_id", articleId);
        Article article = articleMapper.selectOne(articleQueryWrapper);
        article.setGoods(article.getGoods() + 1);
        articleMapper.update(article, articleQueryWrapper);
        return R.ok(article);
    }

    // 发起请求http://localhost:9091/study/article/goods/${articleId}/goods来更新点赞数
    @RequestMapping("/goods/{articleId}/goods")
    public R addGoods2(@PathVariable int articleId) {
        QueryWrapper<Article> articleQueryWrapper = new QueryWrapper<>();
        articleQueryWrapper.eq("article_id", articleId);
        return R.ok(articleMapper.selectOne(articleQueryWrapper));
    }

    @RequestMapping("/commentsCount/{articleId}/commentsCount")
    public R commentsCount(@PathVariable int articleId) {
        QueryWrapper<Article> articleQueryWrapper = new QueryWrapper<>();
        articleQueryWrapper.eq("article_id", articleId);
        return R.ok(articleMapper.selectOne(articleQueryWrapper));
    }

    //  @RequestMapping("/addArticle")
    //  public R addArticle(HttpServletRequest request, @RequestBody ArticleAdd articleAdd){
    //      //从token中获取用户id
    //      String token = request.getHeader(SystemConfig.HEADER_TOKEN);
    //      Integer id = ((NumberWithFormat) JwtUtil.parseToken(token, "id")).intValue();
    //      Article article = new Article();
    //      article.setUserId(id);
    //      article.setCategory(articleAdd.getCategory());
    //      article.setTitle(articleAdd.getTitle());
    //      article.setContent(articleAdd.getContent());
    //      SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    //      article.setCreatedAt(simpleDateFormat.format(new Date()));
    //      article.setUpdatedAt(simpleDateFormat.format(new Date()));
    //      //遍历articleAdd.getFiles()
    //      for (String file : articleAdd.getFiles()) {
    //          String url = AliOssUtil.getUrl("gp-kaoyan", file);
    //          Static static1 = new Static();
    //          static1.setArticleId(article.getArticleId());
    //          static1.setFileUrl(url);
    //          static1.setCreatedAt(new Date());
    //          staticMapper.insert(static1);
    //      }
    //      articleMapper.insert(article);
    //      return R.ok();
    // }
    @RequestMapping("/addArticle")
    public R addArticle(HttpServletRequest request, @RequestBody ArticleAdd articleAdd) {
        try {
            // 解析用户ID
            String token = request.getHeader(SystemConfig.HEADER_TOKEN);
            Integer id = ((NumberWithFormat) JwtUtil.parseToken(token, "id")).intValue();

            // 创建文章对象
            Article article = new Article();
            article.setTitle(articleAdd.getTitle());
            article.setCategory(articleAdd.getCategory());
            article.setContent(articleAdd.getContent());
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            article.setCreatedAt(simpleDateFormat.format(new Date()));
            article.setUpdatedAt(simpleDateFormat.format(new Date()));
            article.setUserId(id);
            // 插入文章到数据库
            articleMapper.insert(article);
            // 处理上传的图片
            for (String image : articleAdd.getUrlList()) {
                Static staticResource = new Static();
                staticResource.setArticleId(article.getArticleId());
                staticResource.setFileUrl(image);
                staticResource.setCreatedAt(new Date());
                staticMapper.insert(staticResource);
            }
            return R.ok();
        } catch (Exception e) {
            return R.fail("上传失败");
        }
    }
}

